//
//  ViewController.swift
//  CalculatorDemo
//
//  Created by 一川 on 3/25/15.
//  Copyright (c) 2015 teng. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var display: UILabel!
    
    var userIsInTheMiddleOfTypingANumber = false;
    var brain = CalculatorBrain()
    
    override func viewDidLoad() {
        let color: UIColor? = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
        display.shadowColor = color
        display.shadowOffset = CGSize(width: 2, height: 2)
        display.textColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1)
        display.numberOfLines = 1
    }
    
    @IBAction func appendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        sender.tintColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
        if userIsInTheMiddleOfTypingANumber{
            display.text = display.text! + "\(digit)"
        }else{
            if digit != "0" {
                display.text = digit
                userIsInTheMiddleOfTypingANumber = true
            }
        }
        
    }
    @IBAction func operate(sender: UIButton) {
        if userIsInTheMiddleOfTypingANumber {
            enter()
        }
        if let operation = sender.currentTitle {//将操作符放入opStack
            brain.pushOperation(operation)
        }
    }
    
    @IBAction func equal() {
        enter()
        if let result = brain.evaluate() {
            displayValue = result
        } else {
            display.text = "ERROR"
        }
    }
    
    @IBAction func clearAll() {//清除记录
        display.text = "0"
        brain.clear()
    }
    
    func enter() {
        userIsInTheMiddleOfTypingANumber = false
        brain.pushOperation(display.text!)
    }
    
    var displayValue:Double{
        get{
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set{
            display.text = "\(newValue)"
        }
    }
}

